﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using ESBasic;
using ESBasic.Helpers;
using System.Configuration;

namespace AutoUpdater
{
    /// <summary>
    /// 说明：
    /// OAUS使用的是免费版的通信框架ESFramework，最多支持10个人同时在线更新。如果要突破10人限制，请联系 www.oraycn.com
    /// </summary>
    public partial class MainForm : Form
    {
        private string mainPath = "main"; //主程序目录
        private string ServerUrl;
        private string callBackExeName;
        private string title;
        private string processName;
        private bool startAppAfterClose = false; //关闭升级窗体前，是否启动应用程序。
        private string currentVersion;
        private string startDirectoryPath;

        private CsUpdateSelf updater;    //
        private CsUpdater csUpdater;

        public MainForm()
        {
            ServerUrl = ConfigurationManager.AppSettings["ServerUrl"];
            callBackExeName = ConfigurationManager.AppSettings["CallbackExeName"];
            title = ConfigurationManager.AppSettings["Title"];
            processName = callBackExeName.Substring(0, callBackExeName.Length - 4);
            startDirectoryPath = System.Windows.Forms.Application.StartupPath;

            updater = new CsUpdateSelf();
            csUpdater = new CsUpdater(mainPath);

            updater.UpdateCompleted += Updater_UpdateCompleted;
            csUpdater.UpdateCompleted += CsUpdater_UpdateCompleted;
        }

        private void CsUpdater_UpdateCompleted(string obj)
        {
            RunMainExe();
        }

        private void Updater_UpdateCompleted(bool arg1, string arg2)
        {
            if(arg1)
            {
                if(!string.IsNullOrEmpty(arg2))
                {
                    RunUpdateExe(arg2);
                }
                else
                {
                    csUpdater.Start();
                }
            }
        }

        public void RunMainExe()
        {
            try
            {
                string processName = this.callBackExeName.Substring(0, this.callBackExeName.Length - 4);
                ESBasic.Helpers.ApplicationHelper.ReleaseAppInstance(processName);

                if (!this.startAppAfterClose)
                {
                    return;
                }

                string filename = Path.Combine(startDirectoryPath, this.callBackExeName);
                if (File.Exists(filename))
                {
                    System.Diagnostics.Process myProcess = System.Diagnostics.Process.Start(filename);
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
        }

        public void RunUpdateExe(string arg2)
        {
            try
            {
                string processName = arg2.Substring(0, arg2.Length - 4);
                ESBasic.Helpers.ApplicationHelper.ReleaseAppInstance(processName);

                if (!this.startAppAfterClose)
                {
                    return;
                }

                string filename = Path.Combine(startDirectoryPath, arg2);
                if (File.Exists(filename))
                {
                    System.Diagnostics.Process myProcess = System.Diagnostics.Process.Start(filename);
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {

        }

        private void SetProgress(ulong total, ulong transmitted)
        {
            if (this.InvokeRequired)
            {
                object[] args = { total, transmitted };
                this.BeginInvoke(new CbGeneric<ulong, ulong>(this.SetProgress), args);
            }
            else
            {
                this.progressBar1.Maximum = 1000;
                this.progressBar1.Value = (int)(transmitted * 1000 / total);

                TimeSpan span = DateTime.Now - this.lastShowTime;
                if (span.TotalSeconds >= 1)
                {
                    this.lastShowTime = DateTime.Now;
                    this.label_progress.Text = string.Format("{0}/{1}", PublicHelper.GetSizeString(transmitted), PublicHelper.GetSizeString(total));
                }
            }
        }

        void updater_UpdateContinued()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new CbGeneric(this.updater_UpdateContinued));
            }
            else
            {
                //this.label_reconnect.Visible = false;
                this.label_reconnect.Text = "重连成功，正在续传...";
            }
        }

        private DateTime lastShowTime = DateTime.Now;
    }
}
